package com.yuan.kafkastudy.KafkaTest;

import com.fasterxml.jackson.databind.deser.std.StringDeserializer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.junit.jupiter.api.Test;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

public class PartitionConsumer {
    private static final String TOPIC = "demo-partitioned";
    private static final String GROUP = "g1";

    @Test
    public void test() {
        Properties p = new Properties();
        p.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        p.put(ConsumerConfig.GROUP_ID_CONFIG, GROUP);
        p.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        p.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        p.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

        try (KafkaConsumer<String, String> cons = new KafkaConsumer<>(p)) {
            cons.subscribe(Collections.singletonList(TOPIC));

            while (true) {
                ConsumerRecords<String, String> recs = cons.poll(Duration.ofMillis(500));
                for (ConsumerRecord<String, String> r : recs) {
                    System.out.printf("Consumer@%s  partition=%d  key=%s  value=%s%n",
                            r.partition() % 2,   // 假装标记消费者 0/1
                            r.partition(),
                            r.key(),
                            r.value());
                }
            }
        }
    }
}